import React from 'react'
import { useState,useReducer } from 'react';
const useSearchParam = param => {
  const getValue = React.useCallback(
    () => new URLSearchParams(window.location.search).get(param),
    [param]
  );

  const [value, setValue] = React.useState(getValue);
  console.debug('%c  value','font-size:30px;',value)
  React.useEffect(() => {
    const onChange = () => {
      setValue(getValue());
    };

    window.addEventListener('popstate', onChange);
    window.addEventListener('pushstate', onChange);
    window.addEventListener('replacestate', onChange);

    return () => {
      window.removeEventListener('popstate', onChange);
      window.removeEventListener('pushstate', onChange);
      window.removeEventListener('replacestate', onChange);
    };
  }, []);

  return value;
};

export default  () => {
  const post = useSearchParam('post');

  return (
    <>
      <p>Post param value: {post || 'null'}</p>
      <button
        onClick={() =>{
            // 使用pushState()方法不会触发popstate事件，只有当浏览器的前进或后退按钮被点击，或者调用history.back(), history.forward(), history.go()时，才会触发popstate事件。
            // 所以这行代码并不会触发onChange事件，也就不会更新value的值。
            window.history.pushState({}, '', window.location.pathname + '?post=42')
        }
        }
      >
        View post 42
      </button>
      <button onClick={() => window.history.pushState({}, '', window.location.pathname)}>
        Exit
      </button>
    </>
  );
};
